-module(element_login).
-include_lib("nitrogen/include/wf.inc").
-compile(export_all).

render(logout) ->
    #link{ text="Se deconnecter", actions=helper:act(?MODULE, logout) };

render(login) ->
    Body = [
	    #p{},
	    #label{ text="Nom d'utilisateur : " },
	    #textbox{ id=nick },

	    #p{},
	    #label{ text="Mot de passe : " },
	    #password{ id=pass },

	    #p{},
	    #checkbox { id=remember_me, text="Rester connecter?", checked=true },

	    #p{},
	    #button{ id=login, text="Connection", actions=helper:act(?MODULE, login)}
	   ],
    wf:wire(login, nick, #validate {
		     validators=[
				 #is_required { text = "Ce champs est obligatoire." }
				] }),
    wf:wire(login, pass, #validate {
		     validators=[
				 #is_required { text = "Ce champs est obligatoire." }
				] }),
    wf:render(Body).

event(login) -> 
    [Nick] = wf:q(nick),
    [Pass] = wf:q(pass),
    Checked = wf:q(remember_me),
    HashedPass = sha2:hexdigest512(Pass),

    case db:validate_member(name, {Nick, HashedPass}) of
	{true, Status} -> wf:user(Nick),
			  wf:session(hpass, HashedPass),
			  wf:session(status, Status),

			  case Checked of
			      [[111,110]] -> 
				  wf_platform:set_cookie(nick, Nick, "/", 43200),
				  wf_platform:set_cookie(hpass, HashedPass, "/", 43200),
				  wf_platform:set_cookie(status, Status, "/", 43200);
			      _ -> ok
			  end,
			  wf:redirect("/web/index");
	{false, _} ->
	    wf:flash("Mauvais nom d'utilisateur / mot de passe")
    end;

event(logout) ->
    wf:clear_session(),
    wf_platform:set_cookie(nick, "", "/", 1),
    wf_platform:set_cookie(hpass, "", "/", 1),
    wf_platform:set_cookie(status, "", "/", 1),
    wf:redirect("/web/index");

event(_) -> ok.


